package com.cgsd.heyu.ui.home.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.library.adapter.ClickTypeListener;
import com.android.library.utils.BeanUtils;
import com.android.library.wedgets.TitleBarView;
import com.apkfuns.logutils.LogUtils;
import com.bun.miitmdid.core.JLibrary;
import com.cgsd.heyu.R;
import com.cgsd.heyu.ad.AdFullVideo;
import com.cgsd.heyu.ad.AdInputScreen;
import com.cgsd.heyu.ad.AdListener;
import com.cgsd.heyu.ad.AdRewardVideo;
import com.cgsd.heyu.ad.AdSplash;
import com.cgsd.heyu.ad.AdSplashDialog;
import com.cgsd.heyu.adapter.TaskAdapter;
import com.cgsd.heyu.api.ApiConfig;
import com.cgsd.heyu.api.AppConfig;
import com.cgsd.heyu.common.AdConstants;
import com.cgsd.heyu.common.CommonConfig;
import com.cgsd.heyu.common.Helper;
import com.cgsd.heyu.common.UserModeConfig;
import com.cgsd.heyu.entity.AdContentEntity;
import com.cgsd.heyu.entity.RewardEntity;
import com.cgsd.heyu.entity.TaskEntity;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.presenter.home.HomeContract;
import com.cgsd.heyu.presenter.home.HomePresenter;
import com.cgsd.heyu.ui.BaseFragment;
import com.cgsd.heyu.ui.news.NewsActivity;
import com.cgsd.heyu.ui.test.TestAdActivity;
import com.cgsd.heyu.ui.webview.CommonH5Activity;
import com.cgsd.heyu.ui.webview.CommonH5SupportImgActivity;
import com.cgsd.heyu.utils.DeviceUtils;
import com.cgsd.heyu.utils.MiitHelper;
import com.cgsd.heyu.utils.PreferencesUtils;
import com.cgsd.heyu.utils.StringUtils;
import com.cgsd.heyu.widgets.dialog.ShareRewardDialog;
import com.pceggs.workwall.util.PceggsWallUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaoxing
 * Description 广告任务
 * CreateData: 2020/11/3
 */
@Deprecated
public class TaskAdFragment extends BaseFragment implements
        TitleBarView.TitleBarClickListener, HomeContract.ClassifyView, View.OnClickListener {
    /**
     * 任务点击按钮
     */
    public static final int CLICK_TASK_BTN = 4;
    private HomeContract.Presenter mPresenter;
    private TaskAdapter taskAdapter;
    private TitleBarView mTitleBarView;
    private LinearLayout layoutTask;
    private LinearLayout layoutEmpty;
    /**
     * 任务数据
     */
    private List<TaskEntity> taskEntities = new ArrayList<>();

    /**
     * 激励视频广告
     */
    private AdRewardVideo adRewardVideo;
    /**
     * 短视频
     */
    private AdFullVideo adFullVideo;
    /**
     * 大图广告（开屏广告）
     */
    private AdSplash adSplash;
    /**
     * 大图dialog
     */
    private AdSplashDialog adSplashDialog;
    /**
     * 小图广告（插屏广告）
     */
    private AdInputScreen adInputScreen;
    /**
     * 当前任务下标
     */
    private int currentPosition;
    /**
     * 任务成功奖励弹窗
     */
    private ShareRewardDialog shareRewardDialog;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_photogrph;
    }

    @Override
    protected void initView() {
        new HomePresenter(this);
        mTitleBarView = findViewById(R.id.title_bar);
        layoutTask = findViewById(R.id.layout_task);
        layoutEmpty = findViewById(R.id.layout_error);
        RecyclerView mRecyclerViewTask = findViewById(R.id.mRecyclerView_task);

        //任务列表
        mRecyclerViewTask.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerViewTask.setHasFixedSize(true);
        mRecyclerViewTask.setNestedScrollingEnabled(false);
        taskAdapter = new TaskAdapter(mContext, taskEntities);
        mRecyclerViewTask.setAdapter(taskAdapter);
        taskAdapter.setClickTypeListener(taskListener);

        mTitleBarView.setTitleBarClickListener(this);
        findViewById(R.id.layout_game1).setOnClickListener(this);
        findViewById(R.id.layout_game2).setOnClickListener(this);
        findViewById(R.id.iv_image).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        setTaskVisible(CommonConfig.getInstance().isShowDayTask);
        mPresenter.getTodayTask();
        mPresenter.getConfigInfo(null);
    }

    /**
     * 任务点击事件
     */
    private ClickTypeListener taskListener = new ClickTypeListener() {
        @Override
        public void clickTypePosition(View view, int type, int position) {
            TaskEntity entity = taskEntities.get(position);
            if (TaskEntity.COMPLETE.equals(entity.userTaskClickStatus)) {
                return;
            }
            currentPosition = position;
            showAd();
        }
    };

    @Override
    public void leftClick() {

    }

    @Override
    public void rightClick() {
    }

    /**
     * 是否显示任务列表
     */
    private void setTaskVisible(boolean isShow) {
        if (isShow) {
            layoutEmpty.setVisibility(View.GONE);
            layoutTask.setVisibility(View.VISIBLE);
        } else {
            layoutEmpty.setVisibility(View.VISIBLE);
            layoutTask.setVisibility(View.GONE);
        }
    }

    @Override
    public void setTaskList(List<TaskEntity> taskList) {
        if (taskList == null) {
            return;
        }
        taskEntities.clear();
        taskEntities.addAll(taskList);
        taskAdapter.notifyDataSetChanged();

        LogUtils.e("setTaskList "+taskEntities.toString());
    }

    @Override
    public void taskRewordSuccess(RewardEntity entity) {
        if (entity == null) {
            return;
        }
        // TODO: 2021/4/19
        LogUtils.e("获得奖励");
        mPresenter.getTodayTask();
        showRewardDialog(entity.awardNum);
    }

    @Override
    public void setConfig(String sysType) {
        setTaskVisible(CommonConfig.getInstance().isShowDayTask);
    }

    @Override
    public void setPresenter(HomeContract.Presenter presenter) {
        mPresenter = BeanUtils.checkNotNull(presenter);
    }

    @Override
    public void setErrorMessage(ErrorMessage error) {
        handleErrorAction(error);
    }

    /**
     * 展示广告
     */
    private void showAd() {
        AdContentEntity entity = new AdContentEntity(AdContentEntity.CHUANSHANJIA, taskEntities.get(currentPosition).advertisingId);
//        entity.advertisingId = "945933282";
        LogUtils.e("type" + taskEntities.get(currentPosition).taskType + "\n" + entity.toString());

        switch (taskEntities.get(currentPosition).taskType) {

            case TaskEntity.REWARD_VIDEO:
                showLoadingView("");
                if (adRewardVideo == null) {
                    adRewardVideo = new AdRewardVideo((Activity) mContext, entity, adListener);
                }
                adRewardVideo.loadAd();
                break;
            case TaskEntity.FULL_VIDEO:
                showLoadingView("");
                if (adFullVideo == null) {
                    adFullVideo = new AdFullVideo((Activity) mContext, entity, adListener);
                }
                adFullVideo.loadAd();
                break;
            case TaskEntity.SPLASH:
                showLoadingView("");
                if (adSplash == null) {
                    adSplash = new AdSplash((Activity) mContext, entity, null, adListener);
                }
                if (adSplashDialog == null) {
                    adSplashDialog = new AdSplashDialog(mContext, adSplash);
                }
                adSplash.loadAd();
                break;
            case TaskEntity.UNIFIED_INTERSTITIAL:
                showLoadingView("");
                if (adInputScreen == null) {
                    adInputScreen = new AdInputScreen((Activity) mContext, entity, adListener);
                }
                adInputScreen.loadAd();
                break;
            case TaskEntity.WEB_AD:
                CommonH5SupportImgActivity.actionStart((Activity) mContext,
                        ApiConfig.API_WEB_AD + UserModeConfig.getInstance().userId, null);

                break;

            case TaskEntity.LOOK_NEWS:
                NewsActivity.start(getActivity());
                break;
            case TaskEntity.XW_GAME:
                loadGame();
                break;
            default:
        }
    }

    private AdListener adListener = new AdListener() {

        @Override
        public void onSuccess() {
            super.onSuccess();
            dismissCommonSubmitDialog();
            if (TaskEntity.SPLASH.equals(taskEntities.get(currentPosition).taskType) && adSplashDialog != null) {
                adSplashDialog.show();
            }
        }

        @Override
        public void onFail() {
            super.onFail();
            dismissCommonSubmitDialog();
            showToast("加载任务失败");
        }

        @Override
        public void onVideoComplete() {
            super.onVideoComplete();
            LogUtils.e("任务onVideoComplete监听");
            // TODO: 2021/4/19
            dismissCommonSubmitDialog();
            if (adSplashDialog != null) {
                adSplashDialog.dismiss();
            }
            mPresenter.getTaskReword(taskEntities.get(currentPosition).taskId);
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        clear();
    }

    /**
     * 清楚广告资源
     */
    private void clear() {
        if (adRewardVideo != null) {
            adRewardVideo.clear();
        }
        if (adFullVideo != null) {
            adFullVideo.clear();
        }
        if (adInputScreen != null) {
            adInputScreen.clear();
        }
    }

    /**
     * 奖励积分弹窗
     *
     * @param num
     */
    private void showRewardDialog(String num) {
        if (shareRewardDialog == null) {
            shareRewardDialog = new ShareRewardDialog(mContext, AdConstants.TASK_REWORD_BANNER);
        }
        shareRewardDialog.setFlowerNum(num);
        shareRewardDialog.show();

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.layout_game1) {
            showToast("功能正在开发中~");
            //NewsActivity.start(getActivity());
        } else if (v.getId() == R.id.layout_game2) {
            loadGame();
        } else {
            //
//            loadGame();
            TestAdActivity.startAction(getActivity());
        }
    }




    private void loadGame() {
        String xwdeviceid;
        if (Build.VERSION.SDK_INT <= 28) {
            xwdeviceid = DeviceUtils.getIMEI(mContext, 0) + "," + DeviceUtils.getIMEI(mContext, 1) + "," + DeviceUtils.getMEID(mContext);
        } else {
            xwdeviceid = DeviceUtils.getDeviceId(mContext);
        }

        LogUtils.e("loadGame"+xwdeviceid+"\n"+UserModeConfig.getInstance().userId+"\n"+DeviceUtils.getDeviceId(mContext));
        PceggsWallUtils.loadAd(getActivity(), AppConfig.XW_ID, AppConfig.XW_KEY, UserModeConfig.getInstance().userId + "", DeviceUtils.getDeviceId(mContext), xwdeviceid);
//        PceggsWallUtils.loadAd(getActivity(), "10001", "PCDDXW_CS_10001", UserModeConfig.getInstance().userId + "", DeviceUtils.getDeviceId(mContext), xwdeviceid);
    }


}
